<template>
    <el-row>
    <el-col :span="24">
      <div class="grid-content ep-bg-purple-dark" />
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="12">
        角色:
        <div style="border: 1px solid #ccc;">
        <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="data"
    :props="defaultProps"
    default-expand-all
    :filter-node-method="filterNode"
     @node-click="nodeClick"
  />
    </div>
    </el-col>
    <el-col :span="12">
        权限菜单:
     <div style="border: 1px solid #ccc;">
          <el-tree
    style="max-width: 600px"
    :data="data1"
    show-checkbox
    node-key="id"
    :props="defaultPropsMenu"
    ref="menuTreeRef"
  />
     </div>
     <el-button type="primary" @click="Save()"  style="float: right; margin-bottom: 250px;">保存</el-button>
    </el-col>
    
  </el-row>
  

</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, type FilterNodeMethodFunction,ElTree, type TreeInstance } from 'element-plus'
import http from '../lanjieqi/lan1'
import axios from '../lanjieqi/lan'

interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()
const menuTreeRef = ref<InstanceType<typeof ElTree>>();
const defaultProps = {
  children: 'children',
  label: 'roleName',
  id: 'id',
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

const data =ref([])
const seach=()=>
{
    axios.get("api/RoleMenu/GetRole").then(res=>
    {
       data.value=res.data.data
    })
}
onMounted(()=>
{
    seach()
    GetMenu()
})


const defaultPropsMenu = {
  children: 'children',
  label: 'menuName',
  id: 'id',
}
const data1 =ref([])

const GetMenu=()=>
{
    axios.get("api/Menu/GetShow").then(res=>
    {
        data1.value=res.data.data
    })
}
const query=reactive
({
  rId:'',
  mId:[] as any[],
  
})
const nodeClick=(x:any)=>
{
    console.log(x);
    query.rId=x.id
    getmenu(x.id)
}
const getmenu=(id:any)=>
{
    axios.get("api/RoleMenu/GetMenuRoleId",{params:{rId:id}}).then(res=>
    {
     console.log(res.data.data);
     
        query.mId=res.data.data.map((item:any)=>item.mId);
        menuTreeRef.value?.setCheckedKeys(query.mId,true);
    })
}

//保存
const Save=()=>
{

  query.mId = menuTreeRef.value!.getCheckedKeys(false)
  http.post("api/RoleMenu/AddRoleMenu",query).then(res=>
  {
    
    
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      
    }
    else
    {
      ElMessage.error(res.data.message)
    }
  })
}
</script>